import axios, { type Method } from 'axios';
import { BaseData, HttpResult, ListResult, ModCondition } from './types';



export default class Http {
    static getToken(): string | null {
        return 'U2FsdGVkX19MhUhi01yvnihyYLg/s7ZnrUx3EtM6Njbg/xYig4ius0vX/79fGz3N';
    }

    static host = 'http://localhost:3001'

    static fastList<T>(module: string): Promise<T[] | null> {
        return this.request<T[]>('get', '/api/mod/fastList', {module});
    }



    static findById<T>(module: string, id: number): Promise<T | null> {
        return this.request<T>('get', '/api/mod/findById', {module, id});
    }

    static removeByIds(module: string, ids: number[]): Promise<number | null> {
        return this.request('post', '/api/mod/remove', {module, ids});
    }

    static insertOrUpdate(
        data: any,
        uri = '/api/mod/insertOrUpdate'
    ): Promise<number | null> {
        return this.request('post', uri, data);
    }

    static select<T extends BaseData>(
        condition: ModCondition<T>,
        url = '/api/mod/list'
    ): Promise<ListResult<T> | null> {
        return this.request<ListResult<T>>('post', url, condition);
    }

    static get<T>(uri: string, data: any): Promise<T | null> {
        return this.request('get', uri, data);
    }

    static post<T>(uri: string, data: any): Promise<T | null> {
        return this.request('post', uri, data);
    }

    static request<T>(method: Method, uri: string, data: any): Promise<T | null> {
        const params = method == 'get' ? data : {};
        return new Promise<T | null>((resolve) => {
            axios
                .request<HttpResult<T>>({
                    url: Http.host+uri,
                    method,
                    params,
                    headers: {
                        token: this.getToken() || '',
                    },
                    data: data,
                })
                .then((res) => {
                    if (res.status == 200) {
                        const {data} = res;
                        if (data.res) {
                            resolve(data.data);
                        } else {
                            resolve(null);
                        }
                    } else {
                        resolve(null);
                    }
                })
                .catch((err) => {
                    resolve(null);
                });
        });
    }
}
